package com.ch.web.controller;

import com.ch.web.annotation.IgnoreLogin;
import com.ch.web.constant.FileConstant;
import com.ch.web.mq.MessageRegister;
import com.ch.web.mq.MqCustomConfigure;
import com.ch.web.mq.RabbitMqCustomTemplate;
import com.ch.web.requestDto.xyUser.RegisterFormDto;
import com.ch.web.requestDto.xyUser.UserLoginFormDto;
import com.ch.web.service.XyUserService;
import com.ch.web.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.File;
import java.io.IOException;

@MultipartConfig
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    XyUserService xyUserService;

    @Autowired
    RabbitMqCustomTemplate rabbitMqCustomTemplate;

    /**
     * 登录
     */
    @IgnoreLogin
    @PostMapping("/login")
    public R login(@RequestBody UserLoginFormDto userLoginFormDto) throws Exception {
        return this.xyUserService.checkLogin(userLoginFormDto);
    }

    /**
     * 判断账号是否存在
     */
    @IgnoreLogin
    @PostMapping("/checkExistsUserName")
    public R checkExistsUserName(@RequestParam("username") String username) {
        return this.xyUserService.checkExistsUserName(username);
    }

    @IgnoreLogin
    @PostMapping("/uploadAva")
    public R uploadAvaFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(FileConstant.FILE_UPLOAD + fileName);
        if (file.exists()) {
            file.delete();
        }
        file = new File(FileConstant.FILE_UPLOAD + fileName);
        multipartFile.transferTo(file);
        String fileUrl = FileConstant.FILE_UPLOAD_URL_PREV + fileName;
        System.out.println(fileUrl);
        return R.ok().put("fileUrl", fileUrl);
    }


    @IgnoreLogin
    @PostMapping("/register")
    public R registerUser(@RequestBody RegisterFormDto registerFormDto) throws InterruptedException {
        rabbitMqCustomTemplate.addMsg(MessageRegister.create(MqCustomConfigure.REGIS_USER, registerFormDto));
        return R.ok();
    }

    @IgnoreLogin
    @PostMapping("/getAvaByName")
    public R getAvaByName(@RequestParam String username) throws InterruptedException {
        String url = xyUserService.getAvaByName(username);
        return R.ok().put("url", url);
    }
}
